package com.qingcheng.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Author:boy
 * @Date:2019/7/25
 * @description:
 * @ModifiedBy:
 */
@Component
public class GoodsDelPageConsumer implements MessageListener {
    private Logger logger = LoggerFactory.getLogger(GoodsAddPageConsumer.class);
    @Reference
    private SkuService skuService;
    @Value("${pagePath}")
    private String pagePath;

    public void onMessage(Message message) {
        try {
            String id = new String(message.getBody(), "utf-8");
            this.delPage(id);
        } catch (UnsupportedEncodingException e) {
            logger.error("消息编码异常", e);
        }

    }

    /**
     * 根据spuId删除商品详情页
     *
     * @param id spuId
     */
    private void delPage(String id) {
        //查询该商品的所有详情页
        List<String> ids = skuService.findIdsBySpuId(id);
        if (ids != null && ids.size() > 0) {
            for (String skuId : ids) {
                File file = new File(pagePath + skuId + ".html");
                if (file.exists()) {//文件存在则删除
                    file.delete();
                }
            }

        }

    }
}
